package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygh.oss.service.OssService;
import com.atguigu.yygh.oss.utils.ConstantOssPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author ybl
 * @version 1.9
 * @date 2021/5/21 13:19
 */
@Service
public class OssServiceImpl implements OssService {

  //上传文件到阿里云oss
  @Override
  public String upload(MultipartFile file) {

    // Endpoint以杭州为例，其它Region请按实际情况填写。
    String endpoint = ConstantOssPropertiesUtil.EDNPOINT;
    String accessKeyId = ConstantOssPropertiesUtil.ACCESS_KEY_ID;
    String accessKeySecret = ConstantOssPropertiesUtil.SECRECT;
    String bucketName = ConstantOssPropertiesUtil.BUCKET;
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    // 生成文件名
    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    String originalFilename = file.getOriginalFilename();
    // 以日期创建文件夹
    String date = new DateTime().toString("yyyy/MM/dd");
    String fileName = date + "/" + uuid + originalFilename;

    try {
      // 执行上传
      ossClient.putObject(bucketName,fileName,file.getInputStream());
      // 返回文件的路径
      return "https://"+bucketName+"."+endpoint+"/"+fileName;
    } catch (IOException e) {
      e.printStackTrace();
    }finally {
      ossClient.shutdown();
    }
    return null;
  }
}
